/**
 * 权限变更监听服务
 * 实现权限变更的实时生效机制
 */

import { menuService } from './menuService';

type PermissionChangeCallback = (permissions: string[]) => void;

class PermissionWatcher {
  private callbacks: PermissionChangeCallback[] = [];
  private currentPermissions: string[] = [];
  private checkInterval: NodeJS.Timeout | null = null;
  private readonly CHECK_INTERVAL = 60000; // 增加到60秒检查一次，减少频率
  private isChecking = false; // 防止并发检查

  /**
   * 启动权限监听
   */
  start(initialPermissions: string[]): void {
    this.currentPermissions = [...initialPermissions];
    
    // 定期检查权限变更
    this.checkInterval = setInterval(() => {
      this.checkPermissionChanges();
    }, this.CHECK_INTERVAL);
  }

  /**
   * 停止权限监听
   */
  stop(): void {
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
      this.checkInterval = null;
    }
  }

  /**
   * 注册权限变更回调
   */
  onPermissionChange(callback: PermissionChangeCallback): () => void {
    this.callbacks.push(callback);
    
    // 返回取消注册函数
    return () => {
      const index = this.callbacks.indexOf(callback);
      if (index > -1) {
        this.callbacks.splice(index, 1);
      }
    };
  }

  /**
   * 手动触发权限检查 - 优化版本，防止并发
   */
  async checkPermissionChanges(): Promise<void> {
    // 防止并发检查
    if (this.isChecking) {
      console.log('权限检查进行中，跳过本次检查');
      return;
    }

    this.isChecking = true;

    try {
      // 这里可以调用API检查当前用户权限
      // 暂时使用localStorage中的用户信息
      const userStr = localStorage.getItem('user');
      if (!userStr) return;

      const user = JSON.parse(userStr);
      const newPermissions = user.permissions || [];

      // 检查权限是否发生变更
      if (this.hasPermissionChanged(newPermissions)) {
        console.log('检测到权限变更，更新菜单...', {
          oldCount: this.currentPermissions.length,
          newCount: newPermissions.length
        });

        this.currentPermissions = [...newPermissions];

        // 清除菜单缓存
        menuService.clearCache();

        // 通知所有监听器
        this.callbacks.forEach(callback => {
          try {
            callback(newPermissions);
          } catch (error) {
            console.error('权限变更回调执行失败:', error);
          }
        });
      }
    } catch (error) {
      console.error('检查权限变更失败:', error);
    } finally {
      this.isChecking = false;
    }
  }

  /**
   * 检查权限是否发生变更
   */
  private hasPermissionChanged(newPermissions: string[]): boolean {
    if (newPermissions.length !== this.currentPermissions.length) {
      return true;
    }
    
    const sortedNew = [...newPermissions].sort();
    const sortedCurrent = [...this.currentPermissions].sort();
    
    return sortedNew.some((permission, index) => permission !== sortedCurrent[index]);
  }

  /**
   * 立即更新权限
   */
  updatePermissions(newPermissions: string[]): void {
    if (this.hasPermissionChanged(newPermissions)) {
      this.currentPermissions = [...newPermissions];
      
      // 清除菜单缓存
      menuService.clearCache();
      
      // 通知所有监听器
      this.callbacks.forEach(callback => {
        callback(newPermissions);
      });
    }
  }

  /**
   * 获取当前权限
   */
  getCurrentPermissions(): string[] {
    return [...this.currentPermissions];
  }
}

// 导出单例
export const permissionWatcher = new PermissionWatcher();
export default permissionWatcher;
